<template>
    <div id="commodity">
        <yd-navbar v-if="routerToCommonid" slot="navbar" :title="goodsNames" class="navbar_header">
            <div v-if="replacePush" @click="routerTo" slot="left">
                <yd-navbar-back-icon></yd-navbar-back-icon>
            </div>
        </yd-navbar>
        <div class="commodity_img">
            <div v-if="goods.goodsImages && goods.goodsImages.length>=1">
                <yd-slider autoplay="3000">
                    <yd-slider-item v-for="(item,index) in goods.goodsImages" :key="index">
                        <img :src="imgUrl+item.goodsImage">
                    </yd-slider-item>
                </yd-slider>
            </div>
            <img v-else :src="goodsImage">
        </div>
        <div class="commodity_box" v-if="goods.goodsName">
            <div class="commodity_title">
                {{goods.goodsName}}
            </div>
            <yd-flexbox class="commodity_money">
                <yd-flexbox-item class="com_money" style="text-align:left">
                    <b>￥</b>
                    <yd-countup v-if="goods.goodsPrice" :endnum="goodsPrice" duration="0.1" decimals="2" separator=","></yd-countup>
                    <span v-else>0</span>
                    <!-- <span class="decoration-price" v-show="goods.scId != 1 && goodsPrice != goodsMarketprice">
                        <b>￥</b>
                        <yd-countup v-if="goods.goodsMarketprice" :endnum="goodsMarketprice" duration="0.1" decimals="2" separator=","></yd-countup>
                        <span v-else>0</span>
                    </span> -->
                </yd-flexbox-item>
                <yd-flexbox-item style="color:#666;text-align:right;line-height:0.8rem;height:0.8rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                    货源：{{goods.storeName}}
                </yd-flexbox-item>
            </yd-flexbox>
            <div class="commodity_center">
                <!--规格  -->
                <div class="spName_list" v-for="(items,indexs) in goods.specList" :key="indexs">
                    <div class="color_box">{{items.spName}}</div>
                    <ul class="fiexd_ul">
                        <li @click="styleBtn(item,indexs,index)" :class="{'active':isActiveStyles[indexs][index]}" v-for="(item,index) in items.specValueList" :key="index">
                            {{item.spValueName}}
                        </li>
                    </ul>
                </div>
            </div>
            <!--购买数量  -->
            <div class="commodity_num">
                <yd-flexbox class="commodity_num_box">
                    <yd-flexbox-item class="com_num" style="text-align:left">
                        购买数量
                    </yd-flexbox-item>
                    <yd-flexbox-item style="text-align:right">
                        <yd-spinner v-model="spinner"></yd-spinner>
                    </yd-flexbox-item>
                </yd-flexbox>
            </div>
            <div class="mobileBody">
                <div v-for="(item,index) in mobileBody" :key='index'>
                    <img :src="item.value" v-if="item.type=='image'">
                    <span v-else>{{item.value}}</span>
                </div>
            </div>
        </div>
        <yd-tabbar slot="tabbar" style="padding:0" :fixed='true'>
            <ul class="commodity_fiexd">
                <li @click="purchase(1)">送朋友</li>
                <li @click="cartBtn">加入购物车</li>
                <li @click="purchase(0)">立即购买</li>
            </ul>
        </yd-tabbar>
        <!--购物车  -->
        <div class="shopping" @click="shoppingCart">
            <yd-icon name="shopcart-outline" size='0.5rem'></yd-icon>
            <yd-badge class="badge" type="danger" v-if="shoppingNum>0">{{shoppingNum}}</yd-badge>
        </div>
    </div>
</template>

<script>
export default {
    name: "commodity",
    data() {
        return {
            imgUrl: this.CONSTANT.imgBaseUrl,
            mobileBody: [],
            goodsImage: "",
            goodsPrice: 0,
            goodsMarketprice: 0,
            commodity: "",
            isActive: [true],
            shoppingNum: 0,
            colors: [
                {
                title: "红色"
                },
                {
                title: "蓝色"
                }
            ],
            isActiveStyles: [],
            styles: [
                {
                title: "A款"
                },
                {
                title: "B款"
                },
                {
                title: "C款"
                }
            ],
            spinner: 0,
            userid: "",
            goodsId: "",
            goods: {},
            goodss: [],
            spValArr: [],
            float: false,
            routerToCommonid: "",
            goodsNames: "",
            replacePush: ""
        };
    },
    created: function() {
        this.userid = this.$store.state.userid;
        let routerTo = this.$store.state.routerTo;
        // 通过商品分享时 routerTo = /commodity?goodsCommonid=xxxx
        // 通过商品一览进入时 routerTo = /
        if (routerTo.indexOf("commodity") != -1) {
            this.routerToCommonid = routerTo;
        } else {
            this.routerToCommonid = "";
        }

        // 通过商品链接进入平台，但没有关注过公众号时,重新设定模式
        // 取得浏览器的信息（无论有没有设定过都需要重新设定）
        let userAgent = navigator.userAgent.toLowerCase();
        // 企业微信浏览器多了wxwork
        if (userAgent.indexOf("wxwork") > -1) {
            this.$store.commit('inMode', 'qiye');
        } else {
            this.$store.commit('inMode', 'weixin');
        }

        if (this.$route.query.goodsCommonid) {
            this.commodity = this.$route.query.goodsCommonid;
        } else {
            this.$router.push("/");
        }
        this.shoppingNum = this.$store.state.cartGoodsNum;
        this.$dialog.loading.open("请稍后");
        this.init(); 
        this.cartGoodsNum();

        // 如果不是通过商品分享进入该页面时
        if (routerTo.indexOf("commodity") == -1) {
            let detailPage = this.$store.state.detailPage || "";
            if (detailPage == undefined || detailPage == "") {
                this.$store.commit("detailPage", "/commodity?goodsCommonid=" + this.commodity);
            } else {
                this.$store.commit("detailPage", "");
            }
        }
        
        // 发送PV统计请求
        _czc.push(["_trackPageview", "/commodity", ""]); 
    },
    mounted: function() {
        document.getElementById("scrollView").scrollTop = 0;
    },
    methods: {
        routerTo() {
            let routerTo = this.$store.state.routerTo;
            if (routerTo.indexOf("commodity") != -1) {
                this.$store.commit("routerTo", "/");
                this.$store.commit("scan", "");
                this.$router.replace(this.replacePush);
            } else {
                this.$router.go(-1);
            }
        },
        init() {
            this.$dialog.loading.open("请稍后");
            this.$axios.get(this.CONSTANT.wapiBaseUrl + "goods/info?goodsCommonid=" + this.commodity)
                .then(response => {
                    this.$dialog.loading.close();
                    if (response.status == 200) {
                        //商品分享
                        let opt = {
                                goodsCommonid: response.data.object.goodsCommonid,
                                name: response.data.object.goodsName,
                                img: response.data.object.goodsImage,
                                inMode: this.$store.state.inMode
                            };
                        this.$store.commit("scan", opt);

                        //分享跳转
                        if (response.data.object.scId == 1) {
                            this.replacePush = "/love";
                        } else {
                            this.replacePush = "/quality";
                        }

                        let apiArr = [];
                        for (var i = 0; i < response.data.object.specList.length; i++) {
                            let arr = [];
                            apiArr.push(arr);
                        }

                        this.isActiveStyles = apiArr;
                        this.goodsImage = this.imgUrl + response.data.object.goodsImage;
                        this.goodsPrice = response.data.object.goodsPrice;
                        this.goodsMarketprice = response.data.object.goodsMarketprice;
                        this.goodsNames = response.data.object.goodsName || "";
                        this.goods = response.data.object;

                        if (response.data.object.goodss.length == 1) {
                            this.goodsId = response.data.object.goodss[0].goodsId;
                            this.float = true;
                        }
                        if (response.data.object.specList.length == 1 && response.data.object.specList[0].specValueList.length == 1) {
                            let arr = [true];
                            this.$set(this.isActiveStyles, 0, arr);
                        }
                        this.goodss = response.data.object.goodss;
                        if (this.goods.mobileBody) {
                            this.mobileBody = JSON.parse(this.goods.mobileBody);
                        }
                    }
                })
                .catch(error => {
                    this.$dialog.loading.close();
                });
        },
        //数组对象方法排序:
        sortByKey(array, key) {
            return array.sort(function(a, b) {
                    var x = a[key];
                    var y = b[key];
                    return x < y ? -1 : x > y ? 1 : 0;
                });
        },
        styleBtn(item, indexs, index) {
            let arr = [];
            this.$set(arr, index, true);
            this.$set(this.isActiveStyles, indexs, arr);
            let spValArr = [];
            this.$set(spValArr, index, item.spValueName);
            spValArr = spValArr.toString().replace(/,/g, "");
            if (spValArr == "默认") {
                spValArr = "N;";
            }
            this.$set(this.spValArr, indexs, spValArr);
            let length = this.spValArr.length;
            let goodsList = this.goodss.filter(o => {
                // 字符串分割成数组、判断是否包含
                let goodsSpecArr = o.goodsSpec.split(",");
                if (length == 1) {
                    return goodsSpecArr.includes(this.spValArr[0]);
                } else if (length == 2) {
                    return (goodsSpecArr.includes(this.spValArr[0]) && goodsSpecArr.includes(this.spValArr[1]));
                } else if (length == 3) {
                    return (goodsSpecArr.includes(this.spValArr[0]) && goodsSpecArr.includes(this.spValArr[1]) && goodsSpecArr.includes(this.spValArr[2]));
                } else if (length == 4) {
                    return (goodsSpecArr.includes(this.spValArr[0]) && goodsSpecArr.includes(this.spValArr[1]) && goodsSpecArr.includes(this.spValArr[2]) && goodsSpecArr.includes(this.spValArr[3]));
                } else if (length == 5) {
                    return (goodsSpecArr.includes(this.spValArr[0]) && goodsSpecArr.includes(this.spValArr[1]) && goodsSpecArr.includes(this.spValArr[2]) && goodsSpecArr.includes(this.spValArr[3]) && goodsSpecArr.includes(this.spValArr[4]));
                } else if (length == 6) {
                    return (goodsSpecArr.includes(this.spValArr[0]) && goodsSpecArr.includes(this.spValArr[1]) && goodsSpecArr.includes(this.spValArr[2]) && goodsSpecArr.includes(this.spValArr[3]) && goodsSpecArr.includes(this.spValArr[4]) && goodsSpecArr.includes(this.spValArr[5]));
                } else if (length == 7) {
                    return (goodsSpecArr.includes(this.spValArr[0]) && goodsSpecArr.includes(this.spValArr[1]) && goodsSpecArr.includes(this.spValArr[2]) && goodsSpecArr.includes(this.spValArr[3]) && goodsSpecArr.includes(this.spValArr[4]) && goodsSpecArr.includes(this.spValArr[5]) && goodsSpecArr.includes(this.spValArr[6]));
                } else if (length == 8) {
                    return (goodsSpecArr.includes(this.spValArr[0]) && goodsSpecArr.includes(this.spValArr[1]) && goodsSpecArr.includes(this.spValArr[2]) && goodsSpecArr.includes(this.spValArr[3]) && goodsSpecArr.includes(this.spValArr[4]) && goodsSpecArr.includes(this.spValArr[5]) && goodsSpecArr.includes(this.spValArr[6]) && goodsSpecArr.includes(this.spValArr[7]));
                }
            });           
            if (this.spValArr.length == this.isActiveStyles.length && goodsList.length == 1) {
                this.float = true;
                this.goodsId = goodsList[0].goodsId;
                this.goodsImage = this.imgUrl + goodsList[0].goodsImage;
                this.goodsPrice = goodsList[0].goodsPrice;
                this.goodsMarketprice = goodsList[0].goodsMarketprice;
            } else {
                this.float = false;
            }
        },
        //购物车商品数量
        cartGoodsNum() {
            this.$axios.get(this.CONSTANT.wapiBaseUrl + "member/statistics")
                .then(response => {
                    if (response.status == 200) {
                        this.shoppingNum = response.data.object.cartGoodsNum;
                        this.$store.commit("cartGoodsNum", response.data.object.cartGoodsNum);
                    }
                })
                .catch(error => {
                    this.$dialog.loading.close();
                });
        },
        //购物车
        cartBtn() {
            if (this.userid) {
                if (this.float) {
                    this.$dialog.loading.open("请稍后");                    
                    // _trackEvent:用于发送页面上按钮等交互元素被触发时的事件统计请求。如视频的“播放、暂停、调整音量”，页面上的“返回顶部”、“赞”、“收藏”等。也可用于发送Flash事件统计请求。
                   // _czc.push(["_trackEvent",category,action,label,value,nodeid]); 
                   //   category: (必填) 表示事件发生在谁身上，如“视频”、“小说”、“轮显层”等等。
                   //   action: (必填) 表示访客跟元素交互的行为动作，如"播放"、"收藏"、"翻层"等等。
                   //   label: (选填) 用于更详细的描述事件，如具体是哪个视频，哪部小说。
                   //   value: (选填) 用于填写打分型事件的分值，加载时间型事件的时长，订单型事件的价格
                   //  nodeid: (选填) 填写事件元素的div元素id(请填写class id，暂不支持name。)
                    _czc.push(["_trackEvent", "购物车", "添加"]); 
                    this.$axios.post(this.CONSTANT.wapiBaseUrl + "cart/add?goodsId=" + this.goodsId + "&qty=" + this.spinner)
                        .then(response => {
                            this.$dialog.loading.close();
                            if (response.status == 200) {
                                if (response.data.status == -1) {
                                    this.$dialog.toast({
                                            mes: response.data.msg,
                                            timeout: 600
                                        });
                                }
                                this.cartGoodsNum();
                            }
                        })
                        .catch(error => {
                            this.$dialog.loading.close();
                        });
                } else {
                    this.$dialog.toast({
                            mes: "请选择规格",
                            timeout: 600
                        });
                }
            } else {
                this.$router.push("/fastLogin");    // 没有权限时，跳转验证码登录
            }
        },
        //去购物车
        shoppingCart() {
           this.$router.push("/shoppingCart");
        },
        purchasePy() {

        },
        //购买
        purchase(numStr) {
            if (this.float) {
                this.$dialog.loading.open("请稍后");
                this.$axios.get(this.CONSTANT.wapiBaseUrl + "checkout/outRight?goods_id=" + this.goodsId + "&quantity=" + this.spinner)
                    .then(response => {
                        this.$dialog.loading.close();
                        if (response.data.status == 1) {
                            let imglist = [
                                    {
                                    goodsImage: this.goodsImage,
                                    spinner: this.spinner,
                                    goodsName: this.goods.goodsName,
                                    goodsPrice: this.goodsPrice,
                                    chooseGoodsSpec: this.spValArr.toString()
                                    }
                                ];
                            this.$store.commit("imglist", imglist);
                            this.$router.push("/pay/purchase?shop=2&pays=" + numStr);
                        } else {
                            this.$dialog.toast({
                                    mes: response.data.msg,
                                    timeout: 600
                                });
                        }
                    });
            } else {
                this.$dialog.toast({
                        mes: "请选择规格",
                        timeout: 600
                    });
            }
        }
    }
};
</script>

<style scoped>
#commodity {
    width: 100%;
    height: auto;
    min-height: 105%;
    padding-bottom: 1rem;
    position: relative;
    overflow: hidden;
    background: #fff;
}

#commodity .commodity_fiexd {
    width: 100%;
    z-index: 9;
    height: 1rem;
    line-height: 1rem;
    text-align: center;
    font-size: 14px;
    background: #dacdba;
    color: #fff;
}

#commodity .mobileBody {
    width: 100%;
    height: auto;
    padding: 15px 0;
    overflow: hidden;
}

#commodity .mobileBody img {
    width: 100%;
    height: auto;
    min-height: 2rem;
    display: block;
    overflow: hidden;
}

#commodity .mobileBody span {
    font-size: 12px;
    text-align: justify;
    color: #4a4a4a;
    line-height: 20px;
}

.spName_list {
    width: 100%;
    height: auto;
    overflow: hidden;
}

.shopping {
    position: fixed;
    right: 5%;
    bottom: 1.5rem;
    z-index: 999;
    width: 1rem;
    text-align: center;
    line-height: 1rem;
    color: #fff;
    font-weight: 400;
    height: 1rem;
    border-radius: 50%;
    background: #f4a9a3;
}

.badge {
    position: absolute;
    right: 0;
    top: -0.1rem;
}

.commodity_fiexd li {
    float: left;
    width: 33.333%;
    height: 100%;
    overflow: hidden;
}

.commodity_fiexd li:nth-of-type(3),
.commodity_fiexd li:nth-of-type(1) {
    background: #c1ad8c;
}

.commodity_img {
    width: 100%;
    height: auto;
    min-height: 4rem;
    overflow: hidden;
}

.commodity_img img {
    width: 100%;
    display: block;
}

.color_box {
    color: #5e5c5d;
    font-size: 16px;
    margin-top: 0.2rem;
    box-sizing: border-box;
    padding: 0 0.1rem;
    line-height: 30px;
}

#commodity .fiexd_ul {
    width: 100%;
    height: auto;
    line-height: 0.6rem;
    font-size: 12px;
    color: #4a4a4a;
    display: flex;
    align-content: left;
    flex-wrap: wrap;
    justify-content: left;
    box-sizing: border-box;
    padding: 0.2rem 0;
    padding-top: 0;
    background: #fff;
    text-align: center;
}

#commodity .fiexd_ul .active {
    background: #c1ad8c;
    color: #fff;
}

#commodity .fiexd_ul li {
    padding: 0 0.3rem;
    margin: 0.1rem;
    background: #f3eee8;
    border-radius: 0.4rem;
}

.commodity_money {
    line-height: 40px;
    font-size: 14px;
    border-bottom: 1px solid #d9d9d9;
}

.commodity_num {
    font-size: 16px;
    padding: 0.2rem 0.1rem;
    box-sizing: border-box;
    border-bottom: 1px solid #d9d9d9;
}

.com_num {
    color: #4a4a4a;
}

.commodity_center {
    width: 100%;
    height: auto;
    overflow: hidden;
    padding-bottom: 0.1rem;
    border-bottom: 1px solid #d9d9d9;
}

.com_money {
    font-size: 18px;
    height: 0.8rem;
    line-height: 0.8rem;
    color: #c00d23;
}

.com_money b {
    font-weight: 400;
    font-size: 12px;
}

.decoration-price {
    margin-left:12px;
    font-size:10px;
    color:#666;
    text-decoration:line-through;
}

.commodity_box {
    width: 100%;
    height: auto;
    min-height: 5rem;
    box-sizing: border-box;
    padding: 0.1rem 0.2rem;
    overflow: hidden;
}

.commodity_title {
    font-size: 16px;
    color: #0d0d0d;
    text-align: justify;
}
</style>